<template>
  <view class="search-page">
    <!-- 搜索栏 -->
    <view class="search-header">
      <view class="search-box">
        <view class="search-box__icon">🔍</view>
        <input 
          class="search-box__input" 
          v-model="keyword"
          placeholder="搜索服务项目"
          focus
          confirm-type="search"
          @confirm="handleSearch"
        />
        <view class="search-box__clear" v-if="keyword" @click="clearKeyword">✕</view>
      </view>
      <view class="search-header__cancel" @click="goBack">取消</view>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-if="!keyword && searchHistory.length > 0 && !searching">
      <view class="search-history__header">
        <text class="search-history__title">搜索历史</text>
        <text class="search-history__clear" @click="clearHistory">清空</text>
      </view>
      <view class="search-history__list">
        <view 
          v-for="(item, index) in searchHistory" 
          :key="index" 
          class="search-history__item"
          @click="useHistoryKeyword(item)"
        >
          <text class="search-history__item-text">{{ item }}</text>
          <text class="search-history__item-time">{{ getHistoryTimeText(index) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 热门搜索 -->
    <view class="search-hot" v-if="!keyword && !searching">
      <view class="search-hot__title">热门搜索</view>
      <view class="search-hot__list">
        <view 
          v-for="(item, index) in hotSearches" 
          :key="index" 
          class="search-hot__item"
          :class="{'search-hot__item--highlight': index < 3}"
          @click="useHotKeyword(item)"
        >
          <text class="search-hot__rank">{{ index + 1 }}</text>
          <text class="search-hot__text">{{ item }}</text>
        </view>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="search-result" v-if="searching || (keyword && searchResults.length > 0)">
      <view v-if="searching" class="search-loading">正在搜索...</view>
      <view v-else class="search-result__list">
        <view class="search-result__header">
          <text class="search-result__count">共找到 {{ searchResults.length }} 个相关服务</text>
        </view>
        <view 
          v-for="(item, index) in searchResults" 
          :key="index" 
          class="search-result__item"
          @click="goToServiceDetail(item.id)"
        >
          <image :src="item.image" mode="aspectFill" class="search-result__image" />
          <view class="search-result__content">
            <view class="search-result__title">{{ item.title }}</view>
            <view class="search-result__desc">{{ item.description }}</view>
            <view class="search-result__bottom">
              <text class="search-result__price">{{ item.price }}</text>
              <text class="search-result__sales">{{ item.sales }}人已下单</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 无搜索结果 -->
    <view class="search-empty" v-if="!searching && keyword && searchResults.length === 0">
      <image class="search-empty__image" src="https://picsum.photos/seed/empty/200/200" mode="aspectFit" />
      <text class="search-empty__text">未找到"{{ keyword }}"相关服务</text>
      <view class="search-empty__tips">
        <text>建议您：</text>
        <text>• 检查输入是否正确</text>
        <text>• 尝试使用其他关键词</text>
        <text>• 浏览服务分类查找</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';

// 搜索关键词
const keyword = ref('');
// 搜索状态
const searching = ref(false);
// 搜索历史
const searchHistory = ref([
  '快递代拿',
  '打印服务',
  '刷乐跑',
  '毕业设计'
]);
// 热门搜索
const hotSearches = ref([
  '快递代拿',
  '远程打印',
  '刷乐跑',
  '毕业设计',
  '代寄快递',
  '课外辅导',
  'KFC早餐',
  '报告打印'
]);
// 搜索结果
const searchResults = ref([]);

// 监听页面加载
onMounted(() => {
  // 获取URL参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options && options.keyword) {
    keyword.value = decodeURIComponent(options.keyword);
    handleSearch();
  }
  
  // 加载本地存储的搜索历史
  loadSearchHistory();
});

// 加载搜索历史
const loadSearchHistory = () => {
  try {
    const history = uni.getStorageSync('searchHistory');
    if (history) {
      searchHistory.value = JSON.parse(history);
    }
  } catch (e) {
    console.error('加载搜索历史失败', e);
  }
};

// 保存搜索历史
const saveSearchHistory = () => {
  try {
    uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value));
  } catch (e) {
    console.error('保存搜索历史失败', e);
  }
};

// 处理搜索
const handleSearch = () => {
  if (!keyword.value.trim()) {
    return;
  }
  
  // 添加到搜索历史
  addToHistory(keyword.value);
  
  // 开始搜索
  searching.value = true;
  
  // 模拟搜索过程
  setTimeout(() => {
    searching.value = false;
    
    // 模拟搜索结果
    searchResults.value = mockSearchResults(keyword.value);
  }, 1000);
};

// 清空关键词
const clearKeyword = () => {
  keyword.value = '';
  searchResults.value = [];
};

// 使用搜索历史
const useHistoryKeyword = (kw) => {
  keyword.value = kw;
  handleSearch();
};

// 使用热门搜索
const useHotKeyword = (kw) => {
  keyword.value = kw;
  handleSearch();
};

// 添加到搜索历史
const addToHistory = (kw) => {
  // 如果已存在则删除旧的
  const index = searchHistory.value.findIndex(item => item === kw);
  if (index !== -1) {
    searchHistory.value.splice(index, 1);
  }
  
  // 添加到最前面
  searchHistory.value.unshift(kw);
  
  // 最多保留10条
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10);
  }
  
  // 保存到本地存储
  saveSearchHistory();
};

// 清空搜索历史
const clearHistory = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        searchHistory.value = [];
        saveSearchHistory();
      }
    }
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取历史搜索时间描述
const getHistoryTimeText = (index) => {
  const times = ['刚刚', '1分钟前', '5分钟前', '1小时前', '昨天', '前天', '3天前', '1周前', '2周前', '1个月前'];
  return times[index] || '较早前';
};

// 跳转到服务详情
const goToServiceDetail = (serviceId) => {
  uni.navigateTo({
    url: `/pages/service/detail?id=${serviceId}`
  });
};

// 模拟搜索结果
const mockSearchResults = (kw) => {
  // 模拟数据库
  const allServices = [
    { 
      id: 1, 
      title: '快递代拿服务', 
      description: '校内各快递点代拿，30分钟内送达',
      image: 'https://picsum.photos/seed/express1/300/200', 
      price: '¥3起', 
      sales: 235,
      keywords: ['快递', '代拿', '代取', '包裹', '取件']
    },
    { 
      id: 2, 
      title: '远程打印服务 黑白/彩印', 
      description: '远程发送文档，快速打印配送',
      image: 'https://picsum.photos/seed/print1/300/200', 
      price: '¥0.5/页起', 
      sales: 189,
      keywords: ['打印', '远程', '文档', '复印', '资料']
    },
    { 
      id: 3, 
      title: '刷乐跑跑腿服务', 
      description: '帮你完成体育锻炼任务，保障达标',
      image: 'https://picsum.photos/seed/run1/300/200', 
      price: '¥8起/公里', 
      sales: 125,
      keywords: ['乐跑', '跑步', '体育', '锻炼', '代跑']
    },
    { 
      id: 4, 
      title: '毕业设计辅导', 
      description: '专业辅导毕业设计，保证质量',
      image: 'https://picsum.photos/seed/study1/300/200', 
      price: '¥200起', 
      sales: 78,
      keywords: ['毕业设计', '设计', '论文', '辅导', '学习']
    },
    { 
      id: 5, 
      title: '快递代寄服务', 
      description: '校内代寄各大快递，无需排队',
      image: 'https://picsum.photos/seed/express2/300/200', 
      price: '¥5起', 
      sales: 158,
      keywords: ['快递', '代寄', '寄件', '包裹', '发件']
    },
    { 
      id: 6, 
      title: 'KFC早餐代购', 
      description: '帮你购买肯德基早餐，准时送达',
      image: 'https://picsum.photos/seed/kfc1/300/200', 
      price: '¥5起', 
      sales: 92,
      keywords: ['KFC', '早餐', '代购', '肯德基', '食物']
    }
  ];
  
  // 过滤匹配结果
  return allServices.filter(service => {
    // 标题匹配
    if (service.title.includes(kw)) {
      return true;
    }
    
    // 描述匹配
    if (service.description.includes(kw)) {
      return true;
    }
    
    // 关键词匹配
    return service.keywords.some(k => k.includes(kw));
  });
};
</script>

<style lang="scss" scoped>
.search-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.search-header {
  background-color: #ffffff;
  padding: 10px 15px;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}

.search-box {
  flex: 1;
  height: 36px;
  background-color: #f5f5f5;
  border-radius: 18px;
  display: flex;
  align-items: center;
  padding: 0 12px;
  margin-right: 10px;
  
  &__icon {
    color: #999;
    margin-right: 8px;
    font-size: 16px;
  }
  
  &__input {
    flex: 1;
    height: 36px;
    font-size: 14px;
  }
  
  &__clear {
    width: 16px;
    height: 16px;
    font-size: 14px;
    color: #999;
    text-align: center;
    line-height: 16px;
  }
}

.search-header__cancel {
  font-size: 14px;
  color: #333;
}

.search-history {
  background-color: #ffffff;
  margin-top: 10px;
  padding: 15px;
  
  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }
  
  &__title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
  
  &__clear {
    font-size: 14px;
    color: #999;
  }
  
  &__list {
    width: 100%;
  }
  
  &__item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 44px;
    
    &-text {
      font-size: 14px;
      color: #333;
    }
    
    &-time {
      font-size: 12px;
      color: #999;
    }
  }
}

.search-hot {
  background-color: #ffffff;
  margin-top: 10px;
  padding: 15px;
  
  &__title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 15px;
  }
  
  &__list {
    width: 100%;
  }
  
  &__item {
    display: flex;
    align-items: center;
    height: 44px;
    
    &--highlight {
      .search-hot__rank {
        background-color: #ff6b6b;
        color: #ffffff;
      }
      
      .search-hot__text {
        font-weight: 500;
      }
    }
  }
  
  &__rank {
    width: 22px;
    height: 22px;
    border-radius: 4px;
    background-color: #f5f5f5;
    color: #999;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
  }
  
  &__text {
    font-size: 14px;
    color: #333;
  }
}

.search-loading {
  display: flex;
  justify-content: center;
  padding: 30px 0;
  color: #999;
  font-size: 14px;
}

.search-result {
  background-color: #ffffff;
  margin-top: 10px;
  
  &__header {
    padding: 15px;
    border-bottom: 1px solid #f5f5f5;
  }
  
  &__count {
    font-size: 14px;
    color: #999;
  }
  
  &__list {
    width: 100%;
  }
  
  &__item {
    display: flex;
    padding: 15px;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  &__image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    margin-right: 12px;
  }
  
  &__content {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  &__title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 5px;
  }
  
  &__desc {
    font-size: 13px;
    color: #999;
    margin-bottom: 10px;
    flex: 1;
  }
  
  &__bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  &__price {
    font-size: 16px;
    font-weight: bold;
    color: #ff6b6b;
  }
  
  &__sales {
    font-size: 12px;
    color: #999;
  }
}

.search-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 0;
  
  &__image {
    width: 120px;
    height: 120px;
    margin-bottom: 20px;
  }
  
  &__text {
    font-size: 16px;
    color: #333;
    margin-bottom: 20px;
  }
  
  &__tips {
    width: 80%;
    font-size: 14px;
    color: #999;
    
    text {
      display: block;
      margin-bottom: 8px;
      line-height: 1.4;
    }
  }
}
</style>
